<?php

/**
 * This is the model class for table "users".
 *
 * The followings are the available columns in table 'users':
 * @property integer $id
 * @property string $username
 * @property string $email
 * @property string $password
 * @property string $timezone
 * @property string $created_at
 * @property string $updated_at
 * @property double $amount
 * @property string $currency
 * @property string $code
 * @property string $tran_cert
 *
 * The followings are the available model relations:
 * @property Transactions[] $transactions
 * @property UserProfiles[] $userProfiles
 */
class User extends CActiveRecord
{
	public $timezone = "Asia/Ho_Chi_Minh";
	public $amount = 0;
	public $currency = "coin";

	public $open_id = "";
	public $open_service = "";

	/*public function defaultScope()
    {
        return array(
            'condition'=>"",
        );
    }*/

    public function scopes()
    {
        return array(
            'openAccount'=>array(
                'condition'=>'username IS NULL',
            ),
            'signedAccount'=>array(
                'condition'=>'username IS NOT NULL',
            )
        );
    }

    public function openAccount()
    {
    	$this->getDbCriteria()->mergeWith(array(
	        'condition'=>'username IS NULL',
	    ));
	    return $this;
    }

	public function signedAccount()
    {
    	$this->getDbCriteria()->mergeWith(array(
	        'condition'=>'username IS NOT NULL',
	    ));
	    return $this;
    }

    public function topTen($order, $limit=10)
    {
    	$this->getDbCriteria()->mergeWith(array(
	        'order'=> $order,
	        'limit'=> $limit,
	    ));
	    return $this;
    }

	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return User the static model class
	 */
	public static function model($className=__CLASS__)
	{
		if(Yii::app()->language == "en"){
			$this->timezone = "America/New_York";
			$this->currency = "gold";
		}
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'users';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('username, email, password', 'required'),
			array('amount', 'numerical'),
			array('username, email', 'length', 'max'=>255),
			array('password', 'length', 'max'=>128),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, username, email, password, timezone, created_at, updated_at, amount, currency', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'transactions' => array(self::HAS_MANY, 'Transaction', 'user_id'),
			'userProfiles' => array(self::HAS_MANY, 'UserProfile', 'user_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'username' => 'Username',
			'email' => 'Email',
			'password' => 'Password',
			'timezone' => 'Timezone',
			'created_at' => 'Created At',
			'updated_at' => 'Updated At',
			'amount' => 'Amount',
			'currency' => 'Currency',
		);
	}

	public function beforeSave(){
		if($this->isNewRecord){
			$init_amount = Setting::model()->findByAttributes(array('type' => 'setting', 'name' => 'init_amount'));
			if(is_object($init_amount)){
				$this->amount = $init_amount->value;
				$this->tran_cert = crypt($this->amount, blowfishSalt());
			}
			$this->created_at = date('Y-m-d h:i:s');
		}else{
			$this->updated_at = date('Y-m-d h:i:s');
		}
		return parent::beforeSave();
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('username',$this->username,true);
		$criteria->compare('email',$this->email,true);
		$criteria->compare('password',$this->password,true);
		$criteria->compare('timezone',$this->timezone,true);
		$criteria->compare('created_at',$this->created_at,true);
		$criteria->compare('updated_at',$this->updated_at,true);
		$criteria->compare('amount',$this->amount);
		$criteria->compare('currency',$this->currency,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	public function getCurrencyLabel($type){
		$arr = array(
			'coin' => 'coin',
			'gold' => 'gold'
		);
		return (isset($arr[$type]))?$arr[$type]:"";
	}

	public function newUserCode(){
		$t = false;
		$new_code = "";
		while($t != true){
			$new_code = sprintf('%08d', mt_rand(00000000,99999999));
			$c = $this->countByAttributes(array('code' => $new_code));
			if($c == 0){
				$t = true;
			}
		}
		return $new_code;
	}

	public function sendMailActive(){
		$subject = Yii::t('lbl', '0010');
		$link = Yii::app()->params['domain'].Yii::app()->createUrl('user/active?code='.$this->code.'&active_code='.$this->active_code);

		$mail = new YiiMailer();
		$mail->setView('mailactive');
		$mail->setData(array('link' => $link, 'name' => $this->username));

		$mail->setFrom(Yii::app()->params['noreplyMail']);
		$mail->setTo($this->email);
		$mail->setSubject($subject);

        return $mail->send();
	}

	public function sendResetPassword(){
		$this->update();
		$subject = Yii::t('lbl', '0013');
		$link = Yii::app()->createUrl('user/resetPassword/code/'.$this->code.'/reset_code/'.$this->reset_code);

		$mail = new YiiMailer();
		$mail->setView('mailforgotpass');
		$mail->setData(array('link' => $link, 'name' => $this->username));

		$mail->setFrom(Yii::app()->params['noreplyMail']);
		$mail->setTo($this->email);
		$mail->setSubject($subject);

        return $mail->send();
	}

	public function resetPassword($new_pass){
		$this->password = crypt($new_pass, blowfishSalt());
		$this->reset_code = null;
		return $this->update();
	}

	public function upsert(){
		$result = false;
		if($this->isNewRecord){
			$this->password = crypt($this->password, blowfishSalt());
			$this->code = $this->newUserCode();
			$this->active_code = crypt($this->username, blowfishSalt());
			$this->status = false;
			$result = $this->insert();
			if($result){
				$this->sendMailActive();
			}
		}else{

		}
		return $result;
	}

	public function createOpenUser($id, $name, $service){
		$anonymous_acc = md5($id);
 		$this->username = $anonymous_acc;
 		$this->email = $anonymous_acc;
 		$this->password = $anonymous_acc."@gameonline.com";
 		$this->open_id = $id;
 		$this->open_service = $service;
 		$this->code = $this->newUserCode();
 		$result = $this->insert();
 		if($result){
 			$user_profile = new UserProfile;
 			$user_profile->first_name = $name;
 			$user_profile->full_name = $name;
 			$user_profile->user_id = $this->id;
 			$user_profile->insert();
 		}
 		return $result;
	}

	public function getStatusHtml(){
		if($this->status)
			return '<span class="label label-success">đã kích hoạt</span>';
		return '<span class="label">chưa kích hoạt</span>';
	}
}